//
//  ChoosePhotos.m
//  Bee
//
//  Created by 汤文洪 on 2017/5/4.
//  Copyright © 2017年 JR.TWH. All rights reserved.
//

#define iOS7Later ([UIDevice currentDevice].systemVersion.floatValue >= 7.0f)
#define iOS8Later ([UIDevice currentDevice].systemVersion.floatValue >= 8.0f)
#define iOS9Later ([UIDevice currentDevice].systemVersion.floatValue >= 9.0f)
#define iOS9_1Later ([UIDevice currentDevice].systemVersion.floatValue >= 9.1f)

#define kPItemWidth ((ScreenW - 30 - 20 ) / 3)
#define kPItemHeight (kPItemWidth/1.56)

#import "ChoosePhotos.h"
#import <AVFoundation/AVFoundation.h>
#import "TZImagePickerController.h"
#import "UIView+TZLayout.h"
#import "TZTestCell.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <Photos/Photos.h>
#import "TZImageManager.h"

#import "ImageBrowserViewController.h"

static ChoosePhotos *getImage = nil;

@interface ChoosePhotos()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,TZImagePickerControllerDelegate,UICollectionViewDataSource,UICollectionViewDelegate>
{
    UIViewController *_fatherViewController;
    BOOL _isSelectOriginalPhoto;
}

@property (nonatomic, strong) UIImagePickerController *imagePickerVc;
/**最大张数*/
@property (nonatomic,assign)NSInteger MaxCount;

@end

@implementation ChoosePhotos
static NSString *const itemID = @"photoCollectIdentifier";

//-(NSMutableArray *)selectedAssets{
//    if (!_selectedAssets) {
//        _selectedAssets = [[NSMutableArray alloc]init];
//    }return _selectedAssets;
//}
//
//-(NSMutableArray *)selectedPhotos{
//    if (!_selectedPhotos) {
//        _selectedPhotos = [[NSMutableArray alloc]init];
//    }return _selectedPhotos;
//}

-(UICollectionView *)photoCollect{
    if (!_photoCollect) {
        _photoCollect = [UICollectionView getCollectionviewWithFrame:CGRectZero andVC:self andBgColor:[UIColor whiteColor] andFlowLayout:[UICollectionView getCollectFlowLayoutWithMinLineSpace:10 andMinInteritemSpacing:10 andItemSize:CGSizeMake(kPItemWidth,kPItemHeight) andSectionInsert:UIEdgeInsetsMake(15, 15, 15, 15) andscrollDirection:UICollectionViewScrollDirectionVertical] andItemClass:[TZTestCell class] andReuseID:itemID];
    }return _photoCollect;
}

- (UIImagePickerController *)imagePickerVc {
    if (_imagePickerVc == nil) {
        _imagePickerVc = [[UIImagePickerController alloc] init];
        _imagePickerVc.delegate = self;
        // set appearance / 改变相册选择页的导航栏外观
        _imagePickerVc.navigationBar.barTintColor = ThemeColor;
        _imagePickerVc.navigationBar.tintColor = ThemeColor;
        UIBarButtonItem *tzBarItem, *BarItem;
        if (iOS9Later) {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[TZImagePickerController class]]];
            BarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UIImagePickerController class]]];
        } else {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[TZImagePickerController class]]];
            
            BarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UIImagePickerController class]]];
        }
        NSDictionary *titleTextAttributes = [tzBarItem titleTextAttributesForState:UIControlStateNormal];
        [BarItem setTitleTextAttributes:titleTextAttributes forState:UIControlStateNormal];
    }
    return _imagePickerVc;
}


+(ChoosePhotos *)SharedChoseImg{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        getImage = [[ChoosePhotos alloc] init];
    });
    return getImage;
}

-(instancetype)init{
    if (self = [super init]) {
        self.selectedPhotos = [[NSMutableArray alloc]init];
        self.selectedAssets = [[NSMutableArray alloc]init];
        self.netPhotoArr = [[NSMutableArray alloc]init];
    }return self;
}

- (void)showActionSheetInFatherViewController:(UIViewController *)fatherVC delegate:(id<ChoosePhotosDelegate>)aDelegate andMaxCount:(NSInteger )count andInitHeight:(void(^)(CGFloat height))HeightBlock{
    
    if (aDelegate) {
        getImage.ChoseImgdelegate = aDelegate;
    }
    _fatherViewController = fatherVC;
    self.MaxCount = count;
    if (HeightBlock) {
        HeightBlock([self CaculatorTotalHeight]);
    }
    [self AddPhotosClicked];
}

-(void)AddPhotosClicked{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    UIAlertAction *photos = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self pushImagePickerController];
    }];
    UIAlertAction *camera = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [self takePhoto];
    }];
    
    [alert addAction:camera];
    [alert addAction:photos];
    [alert addAction:cancel];
    
    [_fatherViewController presentViewController:alert animated:YES completion:nil];
}

- (void)takePhoto {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if ((authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) && iOS8Later)
    {
        // 无权限 做一个友好的提示
        UIAlertController *alert=[UIAlertController  alertControllerWithTitle:@"未获得授权使用摄像头" message:@"请在iOS'设置-隐私-相机'中打开" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *CanCel=[UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleDefault handler:nil];
        [alert addAction:CanCel];
        [_fatherViewController presentViewController:alert animated:YES completion:nil];
     } else { // 调用相机
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
            self.imagePickerVc.sourceType = sourceType;
            if(iOS8Later) {
                _imagePickerVc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
            }
            [_fatherViewController presentViewController:_imagePickerVc animated:YES completion:nil];
        } else {
            NSLog(@"模拟器中无法打开照相机,请在真机中使用");
        }
    }
    
}


#pragma mark - 拍照
- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        TZImagePickerController *tzImagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9 delegate:self];
        tzImagePickerVc.sortAscendingByModificationDate = NO;
        [tzImagePickerVc showProgressHUD];
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
//        UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
        
        // save photo and get asset / 保存图片，获取到asset
        [[TZImageManager manager] savePhotoWithImage:image completion:^(PHAsset *asset, NSError *error) {
            [[TZImageManager manager] getCameraRollAlbum:NO allowPickingImage:YES needFetchAssets:YES completion:^(TZAlbumModel *model) {
                [[TZImageManager manager] getAssetsFromFetchResult:model.result allowPickingVideo:NO allowPickingImage:YES completion:^(NSArray<TZAssetModel *> *models) {
                    [tzImagePickerVc hideProgressHUD];
                    TZAssetModel *assetModel = [models firstObject];
                    if (tzImagePickerVc.sortAscendingByModificationDate) {
                        assetModel = [models lastObject];
                    }
                    [self.selectedAssets addObject:assetModel.asset];
                    [self.selectedPhotos addObject:image];
                    [self.photoCollect reloadData];
                    [self CaculatorTotalHeight];
                    if ([self.ChoseImgdelegate respondsToSelector:@selector(getImage:andAserts:)]) {
                        [self.ChoseImgdelegate getImage:self.selectedPhotos andAserts:self.selectedAssets];
                    }
                }];
            }];
        }];
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark - 选择图片
- (void)pushImagePickerController
{
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:self.MaxCount > 0 ? self.MaxCount - self.netPhotoArr.count : 1 delegate:self];
    imagePickerVc.isSelectOriginalPhoto = _isSelectOriginalPhoto;
    imagePickerVc.selectedAssets = _selectedAssets; // optional, 可选的
    imagePickerVc.allowTakePicture = NO; // 在内部显示拍照按钮
    imagePickerVc.navigationBar.barTintColor = ThemeColor;
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.allowPickingImage = YES;
    imagePickerVc.allowPickingOriginalPhoto = YES;
    imagePickerVc.sortAscendingByModificationDate = NO;
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
    }];
    if([[[UIDevice
          currentDevice] systemVersion] floatValue]>=8.0) {
    _fatherViewController.modalPresentationStyle=UIModalPresentationOverCurrentContext;
    }
    [_fatherViewController presentViewController:imagePickerVc animated:YES completion:nil];
}

#pragma mark .TZImagePickerControllerDelegate
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    [self.selectedPhotos removeAllObjects];
    [self.selectedAssets removeAllObjects];
    
    [self.selectedPhotos addObjectsFromArray:photos];
    [self.selectedAssets addObjectsFromArray:assets];
    _isSelectOriginalPhoto = isSelectOriginalPhoto;
    [self.photoCollect reloadData];
    [self CaculatorTotalHeight];
    if ([self.ChoseImgdelegate respondsToSelector:@selector(getImage:andAserts:)]) {
        [self.ChoseImgdelegate getImage:self.selectedPhotos andAserts:self.selectedAssets];
    }
}

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingVideo:(UIImage *)coverImage sourceAssets:(id)asset {
    [self.selectedPhotos removeAllObjects];
    [self.selectedAssets removeAllObjects];
    
    [self.selectedPhotos addObject:coverImage];
    [self.selectedAssets addObject:asset];
    [self.photoCollect reloadData];
    [self CaculatorTotalHeight];
    if ([self.ChoseImgdelegate respondsToSelector:@selector(getImage:andAserts:)]) {
        [self.ChoseImgdelegate getImage:self.selectedPhotos andAserts:self.selectedAssets];
    }
}

#pragma mark - Collectionview Delegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.netPhotoArr.count + self.selectedPhotos.count + 1;//网络图片 + 本地选择图片 + 选择图片按钮
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    TZTestCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:itemID forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
    cell.videoImageView.hidden = YES;
    if (indexPath.item == self.netPhotoArr.count + self.selectedPhotos.count) {
        [cell.imageView setImage:self.form_hold_img ? self.form_hold_img : kGetImage(@"lc_mine_tool_add_photo")];
        cell.deleteBtn.hidden=YES;
    }else{
        [cell setLayWithCor:5.0 andLayerWidth:.6 andLayerColor:ThemeColor];
        
        cell.deleteBtn.hidden=NO;
        cell.deleteBtn.tag = indexPath.item + 100;
        [cell.deleteBtn addTarget:self action:@selector(deleteBtnClik:) forControlEvents:UIControlEventTouchUpInside];
        
        if (indexPath.item < self.netPhotoArr.count) {
            if ([self.netPhotoArr[indexPath.item] isKindOfClass:[NSString class]]) {
                [cell.imageView sd_setImageWithURL:[NSURL URLWithString:kFORMAT(@"%@",self.netPhotoArr[indexPath.item])] placeholderImage:kGetImage(@"home_ad_null")];
            }else if ([self.netPhotoArr[indexPath.item] isKindOfClass:[NSDictionary class]]){
                
            }
        }else if (indexPath.item >= self.netPhotoArr.count && indexPath.item < self.netPhotoArr.count + self.selectedPhotos.count){
            if ([self.selectedPhotos[indexPath.item - self.netPhotoArr.count] isKindOfClass:[UIImage class]]) {
                cell.imageView.image = self.selectedPhotos[indexPath.item - self.netPhotoArr.count];
                cell.asset = self.self.selectedAssets[indexPath.item - self.netPhotoArr.count];
            }
        }
    }
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.item == self.netPhotoArr.count + self.selectedPhotos.count) {
        [self AddPhotosClicked];
    }else{
        if (indexPath.item < self.netPhotoArr.count) {
            __block NSMutableArray *whole_url_arr = [[NSMutableArray alloc]init];
            [self.netPhotoArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                [whole_url_arr addObject:kFORMAT(@"%@",obj)];
            }];
            [ImageBrowserViewController show:_fatherViewController type:PhotoBroswerVCTypeModal index:indexPath.item imagesBlock:^NSArray *{
                return whole_url_arr;
            }];
        }else if (indexPath.item >= self.netPhotoArr.count && indexPath.item < self.netPhotoArr.count + self.selectedPhotos.count){
            [ImageBrowserViewController show:_fatherViewController type:PhotoBroswerVCTypeModal index:indexPath.item - self.netPhotoArr.count imagesBlock:^NSArray *{
                return self.selectedPhotos;
            }];
        }
    }
}

#pragma mark - Click Event
- (void)deleteBtnClik:(UIButton *)sender {
    if (sender.tag - 100 < self.netPhotoArr.count) {
        if ([self.ChoseImgdelegate respondsToSelector:@selector(deleteNetPhoto:data:)]) {
            [self.ChoseImgdelegate deleteNetPhoto:sender.tag - 100 data:self.netPhotoArr[sender.tag - 100]];
        }
    }else if (sender.tag - 100 >= self.netPhotoArr.count && sender.tag - 100 < self.netPhotoArr.count + self.selectedPhotos.count){
        [self.selectedPhotos removeObjectAtIndex:sender.tag - 100 - self.netPhotoArr.count];
        [self.selectedAssets removeObjectAtIndex:sender.tag - 100 - self.netPhotoArr.count];
        [self.photoCollect reloadData];
        [self CaculatorTotalHeight];
    }
}

#pragma mark - Private Func
-(CGFloat )CaculatorTotalHeight{
    NSInteger totalCount = (self.netPhotoArr.count + self.selectedPhotos.count + 1);
    NSInteger rowNum = totalCount / 3;
    if (totalCount % 3) {
        rowNum += 1;
    }
    CGFloat totalHeight = (rowNum * kPItemHeight) + ((rowNum - 1) * 10) + (30);
    if (self.ChoosePhotoHeightBlock) {
        self.ChoosePhotoHeightBlock(totalHeight);
    }
    return totalHeight;
}

#pragma mark - Setter
-(void)setSelectedAssets:(NSMutableArray *)selectedAssets{
    _selectedAssets = selectedAssets;
}

-(void)setSelectedPhotos:(NSMutableArray *)selectedPhotos{
    _selectedPhotos = selectedPhotos;
}

-(void)setNetPhotoArr:(NSMutableArray *)netPhotoArr{
    _netPhotoArr = netPhotoArr;
}

-(void)setForm_hold_img:(UIImage *)form_hold_img{
    _form_hold_img = form_hold_img;
    [self.photoCollect reloadData];
}

@end
